<template>
  <div class="choose-user">
    <BasicModal
      wrapClassName="choose-user-modal"
      @register="registerModal"
      showFooter
      hid
      :title="title"
      width="480px"
      @ok="handleSubmit"
      @cancel="handleClose"
      :show-cancel-btn="false"
    >
      <div class="page-main">
        <div class="left">
          <BasicTree
            v-bind="$attrs"
            search
            show-icon
            defaultExpandAll
            checkable
            treeWrapperClassName="h--[calc(100vh-500px)] overflow-auto"
            :treeData="treeData"
            :checkedKeys="selectedKeys"
            :fieldNames="{ key: fieldKey, title: fieldTitle }"
            @check="handleTreeCheck"
            ref="asyncExpandTreeRef"
          >
            <template #icon="{ level }">
              <img :src="level_1" v-if="[0, 1].includes(level)" />
              <img :src="level_3" v-else-if="level === 2" />
            </template>
          </BasicTree>
        </div>
      </div>
    </BasicModal>

    <Select
      v-bind="$attrs"
      :class="{
        'HChooseUser-tag': !disabled,
      }"
      placeholder="请选择"
      mode="tags"
      :token-separators="[',']"
      v-model:value="activeKeys"
      disabled
      @click="showModal"
    />
  </div>
</template>
<script lang="ts" setup name="HChooseUser">
  import { propsObj, DataItem } from './props';
  import { ref, unref, nextTick, onMounted, watch, toRefs } from 'vue';
  import { Select } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';
  import { isArray } from '/@/utils/is';

  import level_1 from '/@/assets/images/choose-person-level-1.png';
  import level_3 from '/@/assets/images/choose-person-level-3.png';

  import { BasicModal, useModal } from '/@/components/Modal';
  import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  import { BasicTree, TreeActionType } from '/@/components/Tree';

  const props = defineProps(propsObj);

  const { fullPath } = toRefs(props);
  const treeData = ref<Array<TreeDataItem>>([]);

  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);

  const selectedKeys = ref<any>([]);
  // let initFlag = true;
  let selectItem: DataItem[] = [];

  const emit = defineEmits(['update:value', 'change']);

  const activeKeys = ref<string[]>([]);

  const [registerModal, { openModal, closeModal }] = useModal();

  function handleTreeCheck(_, { node }) {
    let Ptitle: string[] = [];
    if (unref(fullPath)) {
      Ptitle = getParentTitle(node);
    }

    if (!node.checked) {
      selectItem.push({
        name: unref(fullPath) ? `${Ptitle.join('-')}` : node.title,
        id: node.id,
      });
      selectItem = [...new Set(selectItem.map((i) => JSON.stringify(i)))].map((i) => JSON.parse(i));
    } else {
      selectItem = selectItem.filter((i) => i.id !== node[props.fieldKey]);
    }
  }

  watch(
    () => props.value,
    (v) => {
      if (v && isArray(v)) {
        selectItem = cloneDeep(v);
        activeKeys.value = v.map((el) => el.name);
      }
    },
    { immediate: true },
  );
  onMounted(async () => {
    await getAddressListFn();
    // const data = props.value || [];
    // selectItem = data;
    // activeKeys.value = data.map((el) => el.name);
  });
  function showModal() {
    if (props.disabled) return;
    openModal();
    nextTick(() => {
      getTree()?.expandAll(true);

      selectedKeys.value = isArray(props.value) ? props.value?.map((el) => el.id) : [];
    });
  }

  function handleSubmit() {
    activeKeys.value = selectItem.map((i) => i.name);
    emit('change', selectItem);
    emit('update:value', selectItem);
    closeModal();
  }

  function getParentTitle(node) {
    let Ptitle: string[] = [];
    const recursionTitle = (node) => {
      node.title && Ptitle.unshift(node.title);
      if (node.parent) {
        Ptitle.unshift(node.parent.node.title);

        node.parent.parent && recursionTitle(node.parent.parent);
      } else {
        node.node && Ptitle.unshift(node.node.title);
      }
      return Ptitle;
    };
    recursionTitle(node);
    return Ptitle;
  }
  function handleClose() {
    closeModal();
  }

  function arrayFlagLevel(array, level) {
    if (!array || !array.length) return;
    array.forEach((item) => {
      item.level = level;
      item.title = item[props.fieldTitle];
      item.id = item[props.fieldKey];
      if (item.children && item.children.length) {
        arrayFlagLevel(item.children, level + 1);
      }
    });
  }

  async function getAddressListFn() {
    const apiFn = props.api;
    console.log(apiFn);

    if (!apiFn) {
      new Error('请设置请求接口');
      return;
    }
    const data = await apiFn(props.params);

    arrayFlagLevel(data, 0);
    treeData.value = data;
  }

  function getTree() {
    const tree = unref(asyncExpandTreeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
</script>

<style scoped lang="less">
  .page-main {
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #e9e9e9;
    display: flex;

    .left {
      flex: 1;
      border-right: 1px solid #e9e9e9;
      padding: 12px;
      overflow-y: auto;

      .tree-box {
        margin-top: 8px;
      }
    }

    .mid {
      flex: 1;
      border-right: 1px solid #e9e9e9;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      &-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;
        padding: 12px 12px 0 8px;

        .check-box {
          display: flex;
          align-items: center;
          cursor: pointer;
          user-select: none;

          span {
            margin-right: 8px;
          }
        }
      }

      .overscroll-box {
        flex: 1;
        // height: 400px;
        overflow-y: auto;

        .person-box {
          cursor: pointer;
          padding: 0 12px;
          user-select: none;

          .item {
            display: flex;
            justify-content: space-between;
            // padding: 9px 0 9px 4px;
            min-height: 32px;
            align-items: center;
            margin-bottom: 8px;

            span {
              flex: 1;
              margin-right: 8px;
            }
          }
        }

        .no-data {
          height: 100%;
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }

      &-bottom {
        display: flex;
        flex-wrap: wrap;

        .check-item {
          height: 36px;
          width: 50%;
          display: flex;
          align-items: center;
          padding: 12px;
          cursor: pointer;
          user-select: none;

          &:nth-child(1) {
            border: 1px solid #e9e9e9;
            border-left: none;
          }

          &:nth-child(2) {
            border: 1px solid #e9e9e9;
            border-left: none;
            border-right: none;
          }

          &:nth-child(3) {
            border-right: 1px solid #e9e9e9;
          }

          div {
            margin-right: 8px;
          }
        }
      }
    }

    .right {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .top {
        flex: 1;
        overflow-y: auto;
        padding: 12px 12px 0 12px;

        .item {
          height: 32px;
          padding: 9px 12px;
          background: rgba(43, 99, 161, 0.05);
          border-radius: 2px 2px 2px 2px;
          border: 1px solid rgba(43, 99, 161, 0.3);
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .close-btn {
            cursor: pointer;
          }

          span {
            color: rgba(43, 99, 161, 1);
          }
        }
      }

      .please-choose-person {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        padding-top: 25px;
      }

      .bottom {
        display: flex;
        height: 37px;
        border-top: 1px solid #e9e9e9;
        justify-content: space-between;
        align-items: center;
        padding: 12px;
        color: rgba(43, 99, 161, 1);

        .bottom-left {
          color: #999999;
        }

        .clear-all {
          cursor: pointer;
        }
      }
    }
  }

  ::v-deep(.vben-tree-header) {
    border-bottom: none;
    padding: 0 0 10px 0;
  }

  ::v-deep(.HChooseUser-tag) {
    &.ant-select-disabled {
      .ant-select-selector {
        cursor: pointer !important;
        background: @component-background !important;

        input,
        .ant-select-selection-item {
          cursor: pointer !important;
        }
      }
    }
  }
</style>

<style lang="less">
  .choose-user-modal {
    .scroll-container {
      .scrollbar__wrap {
        margin-bottom: 0 !important;
      }
    }
  }
</style>
